package com.brokendust.client.api.util;

import com.brokendust.client.PixelEngine;

import java.nio.charset.StandardCharsets;

public class NumberUtil {
    public static int stringLength(String text) {
        return PixelEngine.fontRenderer.width(text);
    }

    public static int lengthOfInt(String value) {
        if (value == null) {
            return 0;
        }
        StringBuffer buff = new StringBuffer(value);
        int length = 0;
        for (int i = 0; i < buff.length(); ++i) {
            String stmp = buff.substring(i, i + 1);
            try {
                stmp = new String(stmp.getBytes(StandardCharsets.UTF_8));
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (stmp.getBytes().length > 1) {
                length += 3;
            } else {
                length += 2;
            }
        }
        return length;
    }

    public static boolean lengthOfDS(String value) {
        if (value == null) {
            return false;
        }
        StringBuffer buff = new StringBuffer(value);
        double length = 0.0;
        for (int i = 0; i < buff.length(); ++i) {
            String stmp = buff.substring(i, i + 1);
            try {
                stmp = new String(stmp.getBytes(StandardCharsets.UTF_8));
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (stmp.getBytes().length > 1) {
                length += 1.5;
            } else {
                ++length;
            }
        }
        return (int) (length % 2.0) == 0;
    }

    public static int strLength(String value) {
        int length = 0;
        String str = (value == null) ? "" : value;
        for (int i = 0; i < str.length(); ++i) {
            char character = str.charAt(i);
            if (Character.UnicodeBlock.of(character) != Character.UnicodeBlock.BASIC_LATIN || !isHalfWidth(character)) {
                ++length;
            }
            ++length;
        }
        return length;
    }

    public static boolean isHalfWidth(char c) {
        return c >= '\u0020' && c <= '\u007e';
    }
}

